package me.nujoug.foctapp;

import me.nujoug.net.dao.DateStatus;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Adapter to bind a ToDoItem List to a view
 */
public class DateItemAdapter extends ArrayAdapter<DateStatus> {

	/**
	 * Adapter context
	 */
	Context mContext;

	/**
	 * Adapter View layout
	 */
	int mLayoutResourceId;

	public DateItemAdapter(Context context, int layoutResourceId) {
		super(context, layoutResourceId);

		mContext = context;
		mLayoutResourceId = layoutResourceId;
	}

	/**
	 * Returns the view for a specific item on the list
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;

		final DateStatus currentItem = getItem(position);

		if (row == null) {
			LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
			row = inflater.inflate(R.layout.row_list_date, parent, false);
		}

		row.setTag(currentItem);
		final TextView itemView = (TextView) row.findViewById(R.id.DateItem);
		itemView.setText(currentItem.getDateStr() + " - " + currentItem.getDayInWeek());

		final Button buttom = (Button) row.findViewById(R.id.buttonAppCatch);
		buttom.setText(currentItem.getAppointmentStatus());
		if (currentItem.getAppointmentStatus() == DateStatus.FULL) {
			buttom.setEnabled(false);
		}
		buttom.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(currentItem.getAppointmentStatus().equals(DateStatus.APPOINT)
					||(((DateListActivity)mContext).autoSubmit && currentItem.getAppointmentStatus().equals(DateStatus.CATCH))){
			        Bundle bundle = new Bundle();
			        bundle.putString("hospID", currentItem.getHospID());
			        bundle.putString("depID", currentItem.getDepID());
			        bundle.putString("dateStr", currentItem.getDateStr());
			        bundle.putString("appointmentStatus", currentItem.getAppointmentStatus());
			        ((FoctWebBaseActivity) mContext).passWebData(bundle);
			        Intent intent = new Intent(mContext, DoctListActivity.class);
			        intent.putExtras(bundle);
			        mContext.startActivity(intent);
				}
				
				Toast toast = Toast.makeText(
						mContext.getApplicationContext(),
						currentItem.getAppointmentStatus() + ":"
								+ currentItem.getDateStr(),
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				return;

			}
		});
		return row;
	}

}
